package com.szml.user.utils;

import org.apache.commons.validator.routines.InetAddressValidator;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @Author limin
 * @date 2025-06-21 19:29
 * @description 获取IPv4（AI辅助）
 */
public class IPUtils {
    private static final InetAddressValidator validator = InetAddressValidator.getInstance();

    // 更全面的IP头列表
    private static final List<String> IP_HEADERS = Arrays.asList(
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "X-Real-IP"
    );

    public static String getClientIpv4(HttpServletRequest request) {
        String ip = null;

        // 1. 检查所有可能的代理header
        for (String header : IP_HEADERS) {
            ip = request.getHeader(header);
            if (isValidIpv4(ip)) {
                return ip;
            }
        }

        // 2. 直接获取远程地址
        ip = request.getRemoteAddr();
        if (isValidIpv4(ip)) {
            return ip;
        }

        // 3. 处理本地IPv6
        if ("0:0:0:0:0:0:0:1".equals(ip) || "::1".equals(ip)) {
            return "127.0.0.1";
        }

        return null;
    }

    private static boolean isValidIpv4(String ip) {
        if (ip == null || ip.isEmpty()) return false;

        // 处理多个IP的情况（如X-Forwarded-For: client, proxy1, proxy2）
        if (ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }

        return validator.isValidInet4Address(ip);
    }
}
